package com.tkmybatis.hfy.base.controller;

import java.beans.PropertyEditorSupport;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import com.tkmybatis.exception.EsException;
import com.tkmybatis.hfy.base.entity.Result;
import com.tkmybatis.hfy.utils.DateJsonValueProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.multipart.MaxUploadSizeExceededException;


import net.sf.json.JsonConfig;

/**
 * 公共控制器
 * 
 * @author leo
 *
 */
@ControllerAdvice
public class CommonController {

	private static Logger logger = LoggerFactory.getLogger(CommonController.class);

	@Autowired
	private HttpServletRequest request;

	/**
	 * 获取根路径
	 * 
	 * @author ywt
	 * @date 2018年5月3日 上午11:35:22
	 * @version 1.0
	 * @return
	 */
	public String getBasePath() {
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path
				+ "/";
		return basePath;
	}

	/**
	 * 把值绑定到Model中，使全局@RequestMapping可以获取到该值
	 * 
	 * @param model
	 */
	@ModelAttribute
	public void addAttributes(Model model) {
		model.addAttribute("ctx", request.getContextPath());
	}

	/**
	 * 获取项目URL
	 * 
	 * @author ywt
	 * @date 2018年5月3日 上午11:35:32
	 * @version 1.0
	 * @return
	 */
	public String getBasePathUrl() {
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path
				+ "/";
		return basePath;
	}

	private static String getLocalMac(InetAddress ia) throws SocketException {
		// 获取网卡，获取地址
		byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
		StringBuffer sb = new StringBuffer("");
		for (int i = 0; i < mac.length; i++) {
			if (i != 0) {
				sb.append("-");
			}
			// 字节转换为整数
			int temp = mac[i] & 0xff;
			String str = Integer.toHexString(temp);
			if (str.length() == 1) {
				sb.append("0" + str);
			} else {
				sb.append(str);
			}
		}
		return sb.toString().toUpperCase();
	}

	/**
	 * JSON日期转换配置
	 */
	private JsonConfig jsonConfig;

	public JsonConfig getJsonConfig(String datePattern) {
		logger.info("init jsonConfig...");
		jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor(datePattern));
		jsonConfig.registerJsonValueProcessor(java.sql.Date.class, new DateJsonValueProcessor(datePattern));
		jsonConfig.registerJsonValueProcessor(java.sql.Timestamp.class, new DateJsonValueProcessor(datePattern));
		return jsonConfig;
	}

	@ExceptionHandler(EsException.class)
	public Result runtimeExceptionHandler(EsException e) throws ServletException {
		return Result.fail(e.getCode(), e.getMessage());
	}

	@ExceptionHandler(MethodArgumentNotValidException.class)
	public Result MethodArgumentNotValidHandler(MethodArgumentNotValidException e) throws ServletException {
		if(e != null) {
			String message = e.getBindingResult().getFieldError().getDefaultMessage();
			return Result.fail("201", message);
		}
		return Result.sucess();
	}

	/**
	 * 全局异常处理.
	 */
	@ExceptionHandler(Exception.class)
	public Result runtimeExceptionHandler(final HttpServletRequest request, Exception ex) throws ServletException {
		Result model = new Result();
		if (ex instanceof org.mybatis.spring.MyBatisSystemException) {
			model.setMsg("数据库连接异常!");
			model.setRet("5001");
		} else if (ex instanceof MissingServletRequestParameterException) {
			model.setMsg("请求参数异常:"+ex.getMessage());
			model.setRet("5002");
		} else if (ex instanceof MaxUploadSizeExceededException) {
			model.setMsg("文件过大!");
			model.setRet("50004");
		} else {
			model.setMsg("系统异常!");
			model.setRet("5000");
		}
		logger.error("错误：{}", ex);
		return model;
	}
}
